var argscheck = require('cordova/argscheck');
var utils = require('cordova/utils');
var exec = require('cordova/exec');

var UrovoScanner = function() {};

UrovoScanner.start = function() {
  exec(null, null, 'UrovoScanner', 'start', []);
  return this;
};

UrovoScanner.stop = function() {
  exec(null, null, 'UrovoScanner', 'stop', []);
  return this;
};

// 监听事件urovo.scanner.decode获取扫码得到的数据
window.addEventListener('urovo.scanner.decode', function(event) {
  // console.log(event.detail);
});

// 兼容低版本浏览器
if ('undefined' === typeof CustomEvent && 'function' === typeof document.createEvent) {
  function CustomEvent (type, params) {
    var e = document.createEvent('CustomEvent');
    if (params) {
      e.initCustomEvent(type, params.bubbles, params.cancelable, params.detail);
    } else {
      e.initCustomEvent(type, false, false, void 0);
    }
    return e;
  }
} 

// initialize plugin
document.addEventListener('deviceready', function() {
  exec(
    function(res) {
      window.dispatchEvent(new CustomEvent('urovo.scanner.' + res.event, {
        detail: res.data
      }));
    },
    null,
    'UrovoScanner',
    'init',
    []
  );
});

module.exports = UrovoScanner;